#include "kernel.h"	
#include "util.h"
#include "malloc.h"


/**
 * \file task.c
 * \author Clecio Varjao and Leanne Ross
 * \date October 2007
 * \remarks Based on code created by Dr. Mantis Cheng
 * \brief RTOS task implementation
 */


int Task_Create(void (*f)(void), int arg, unsigned int level, unsigned int name){
	volatile TASK_CONSTRUCTOR *c;
	TASK_EXECUTER *e;
	int ret=0;

	if (level==PERIODIC && name==0){		// periodic not declared in PPP array
		OS_Error(212);
	}

	c = TC_alloc();
	c->code = f;
	c->arg = arg;
	c->level = level;
	c->name = name;

	if (KernelActive){
		Disable_Interrupt();		
		e = (TASK_EXECUTER*)curTE;
		e->request = CREATE;
		e->requestInfo = (TASK_CONSTRUCTOR*)c;
		Enter_Kernel();
	} else{ 
		/* call the RTOS function directly */
		Kernel_Create_And_Schedule((TASK_CONSTRUCTOR*)c);
	}

	return ret;
}

void Task_Next(){
	TASK_EXECUTER *e;

	if (KernelActive){
		Disable_Interrupt();
		e=(TASK_EXECUTER*)curTE;
		e->request = NEXT;
		Enter_Kernel();
	}
}

void Task_Terminate(){
	TASK_EXECUTER *e;

	if (KernelActive){
		Disable_Interrupt();
		e=(TASK_EXECUTER*)curTE;
		e -> request = TERMINATE;
	  	Enter_Kernel();
		/* never returns here! */
	}
}

int Task_GetArg(){
	return curTE->task->info->arg;
}
